home *** CD-ROM | disk | FTP | other *** search
- Path: news.belwue.de!uzwil!kuehl
- From: kuehl@uzwil.informatik.uni-konstanz.de (Dietmar Kuehl)
- Newsgroups: comp.lang.c++
- Subject: Re: template question
- Date: 16 Apr 1996 20:31:58 GMT
- Organization: FakultΣt fⁿr Mathematik und Informatik
- Message-ID: <4l103u$kmn@news.BelWue.DE>
- References: <4l0mk7$4n0@prof.ese-metz.fr>
- Reply-To: dietmar.kuehl@uni-konstanz.de
- NNTP-Posting-Host: uzwil.informatik.uni-konstanz.de
- X-Newsreader: TIN [version 1.2 PL2]
-
- Hi,
-
- Dominique PELLE (Dominique.Pelle@ingenieurs.supelec.fr) wrote:
- : I have a simple problem to solve:
-
- : I would like to have an integer type on n bits and I would like
- : to overload operator+ so that I can use it this way :
-
-
- : integer<7> variable_7bits = 125;
- : integer<4> variable_4bits = 15;
- : integer<7> variable_7bits;
-
- : variable_7bits = variable_7bits + variable_4bits;
-
- : // 'variable_7bits' is now equal to :
- : // -> 125+15
- : // -> 140
- : // -> 12 (because it is on 7 bits)
-
-
- :
- : No matter if it is coded on 32 bits, all it has to do, is perform
- : operations so that it wraps around n bits AND ALSO detects if the
- : operation overflows to warn the user.
-
-
- : The question is :
- : ~~~~~~~~~~~~~~~
-
- : ????????? HOW CAN I WRITE THE OPERATOR+ FUNCTION ??????????
-
- Without member templates, you can do something like this:
-
- template <int N>
- class integer
- {
- private:
- // representation
- public:
- int const *representation(); // ugly, because public: unnecessary
- // with template members...
- integer(int);
- integer(integer<N> const &);
- integer<N> &add(int const *data, int size)
- {
- // do the addition: all information necessary is present
- }
- };
-
- template <int N1, int N2>
- integer<N1> &operator+= (integer<N1> &i1, integer<N2> const &i2)
- {
- return i1.add(i2.representation(), N2);
- }
-
- template <int N1, int N2>
- integer<N1> operator+ (integer<N1> const &i1, integer<N2> const &i2)
- {
- return integer<N1>(i1) += i2;
- }
-
- with member templates, you can make 'representation()' private by
- adding
-
- template <int M>
- friend integer<N> &operator+= (integer<N> &, integer<M> const &);
-
- to the class declaration.
- --
- dietmar.kuehl@uni-konstanz.de
- http://www.informatik.uni-konstanz.de/~kuehl/
- I am a realistic optimist - that's why I appear to be slightly pessimistic
-